package com.itheima.servlet.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

// req.html
// 演示Request通用方式获取请求参数
@WebServlet("/req03")
public class RequestDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.Map<String, String[]> getParameterMap()：获取所有参数Map集合
        Map<String, String[]> parameterMap = req.getParameterMap();
        // 遍历Map, 键找值, Entry键值对方式
        Set<String> keySet = parameterMap.keySet();
        for (String key : keySet) {
            String[] value = parameterMap.get(key);
            System.out.println(key + " : " + Arrays.toString(value));
        }

        System.out.println("--------------------------------------");
        // 2.String getParameter(String name)：根据名称获取参数值（单个值）
        String username = req.getParameter("username");
        System.out.println("username = " + username);

        System.out.println("--------------------------------------");
        // 3.String[] getParameterValues(String name) ：根据名称获取参数值（数组）
        String[] hobbies = req.getParameterValues("hobby");
        System.out.println("hobbies = " + Arrays.toString(hobbies));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost");
        // 我们发现doGet和doPost使用同样方式获取请求参数,没有必要在doGet和doPost中都编写.
        // 我们可以在doPost中直接调用doGet
        doGet(req, resp);
        /*// 1.Map<String, String[]> getParameterMap()：获取所有参数Map集合
        Map<String, String[]> parameterMap = req.getParameterMap();
        Set<Map.Entry<String, String[]>> entrySet = parameterMap.entrySet();
        for (Map.Entry<String, String[]> entry : entrySet) {
            String key = entry.getKey();
            String[] value = entry.getValue();
            System.out.println(key + " :: " + Arrays.toString(value));
        }

        System.out.println("--------------------------------------");
        // 2.String getParameter(String name)：根据名称获取参数值（单个值）
        String username = req.getParameter("username");
        System.out.println("username = " + username);

        System.out.println("--------------------------------------");
        // 3.String[] getParameterValues(String name) ：根据名称获取参数值（数组）
        String[] hobbies = req.getParameterValues("hobby");
        System.out.println("hobbies = " + Arrays.toString(hobbies));*/
    }
}
